//
//  NSDate+Extension.swift
//  FlyBlog
//
//  Created by FEI on 16/4/19.
//  Copyright © 2016年 FEI. All rights reserved.
//

import Foundation

extension NSDate {

    class func date(sinaString:String) -> NSDate {
        let dateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        dateFormatter.locale = NSLocale(localeIdentifier: "EN")

        let date = dateFormatter.dateFromString(sinaString) ?? NSDate()

        return date
    }

    func sinaDateDescription() -> String {
        let calender = NSCalendar.currentCalendar()

        if calender.isDateInToday(self) {
            let delta = Int(NSDate().timeIntervalSinceDate(self))

            if delta < 60 {
                return "刚刚"
            }

            if delta < 60 * 60 {
                return "\(delta / 60)分钟前"
            }

            return "\(delta / 60 / 60)小时前"
        }

        var dateFormat = ""

        if calender.isDateInYesterday(self) {
            print("昨天")
            dateFormat = "昨天 HH:mm"
        }else if calender.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame {
            dateFormat = "MM-dd HH:mm"
        }else {
            dateFormat = "yyyy-MM-dd HH:mm"
        }

        let dateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = dateFormat
        dateFormatter.locale = NSLocale(localeIdentifier: "EN")

        let dateString = dateFormatter.stringFromDate(self)

        return dateString
    }

}
